$(function() {
	$('.detail_header img').bind('click',function(){
		window.location.href = document.referrer; //返回上一页并刷新
	});
	var obj = {
		id: 0, 							//商品id
		type:0,							//商城类型 1、集分商城 2、积分兑换商城 3、零元购
		newPrice: $('.newP'), 			//新价格
		oldPrice: $('.oldP'), 			//旧价格
		info_price: $('.price'), 		//信息框价格
		title: $('.good_name'), 		//商品名称
		stock: $('.Stock'), 			//库存
		info_stock: $('.info_stock'), 	//信息框库存
		info_img: $('.good_img img'), 	//信息框缩略图
		skuArr: [], 					//sku数组
		yuanjia: $('.original_price'),	//原价两个字
		Selected: $('.selected'),		//信息框已选
		skuStock: 0,					//对应的sku商品库存
		goodNum: $('.num')				//信息框商品加减数量
	}
	//获取选中的sku组合
	var skuGroup = null;
	function getSkuGroup (a) {
		return skuGroup = a;
	}
	//获取单个商品sku的库存
	function getSkuStock(b){
		return obj.skuStock = b;
	}
	// 取出商品列表界面传过来的参数  
	function GetRequest() {
		var url = location.search;
		var theRequest = new Object();
		if(url.indexOf("?") != -1) {
			var str = url.substr(1);
			strs = str.split("&");
			for(var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	}
	obj.id = GetRequest().id;
	console.log(obj.id);
	
	//进入商品详情界面首先根据商品的id加载sku数据和详情数据
	showInfo();
	function showInfo() {
		$.ajax({
			url: 'http://a.91jfk.com/Product/Pointshop/goods_detail_data?id=' + obj.id,
			type: 'get',
			dataType: 'json',
			success: function(res) {
				console.log(res);
				if(res.code == "1") {
					var data = res.message;
					var arr = data.loop_pic.split(",");
					// 轮播图
					var Swiper = new SwiperLunBo();
					Swiper.carousel(arr).swiper().changeLunBo(arr); //changeLunBo方法只能在swiperLunBo方法之后调用
					obj.id = data.id;
					obj.type = data.goods_type;
					obj.title.text(data.pname);
					localStorage.setItem('JFSCname',data.pname);		//商品名称
					if (data.single_product == 1) {
						obj.newPrice.text(data.low_price);
						obj.oldPrice.text(data.original_price);
					}else if(data.single_product == 2){
						obj.newPrice.text(data.low_price);
						obj.yuanjia.hide();
						obj.oldPrice.hide();
					}
					obj.stock.text(data.stock);
					obj.info_price.text(data.price_range);
					obj.info_stock.text(data.stock);
					obj.info_img[0].src = data.show_pic;
					var result = HTMLDecode(data.detail_introduce);
					var box = $('.detailImg_box');
					var div = $('<div class="imgBefor"></div>');
					box.append(div.append(result));
				} else {
					console.log('错误');
				}
			},
			error: function(err) {
				console.log(err);
			}
		}); //ajax结束
	}
	
	//进入页面加载商品sku信息
	getSkuData();
	function getSkuData() {
		$.ajax({
			type: "post",
			url: "http://a.91jfk.com/Product/Pointorder/one_sku_data",
			dataType: 'json',
			data: {
				id: obj.id
			},
			success: function(res) {
				console.log(res)
				if(res.code == 1) {
					var data = res.message;
					var obj = {};
					var arr = [];
					$(data).each(function(index, ele) {
						var str = ele.shuxing_zhi;
						var str1 = ele.sku_combination;
						str = '{' + str + ',"skuId":"' + str1 + '"}';
						str = eval("(" + str + ")");
						arr.push(str);
					});
					Sku(arr);
					setTimeout(function(){
						for(var i = 0;i < data.length;i++){
							if ($('.chosePackage').eq(0).children(".change").text() == data[i].color) {
								$('.good_img img')[0].src = data[i].show_pic;
							}
						}
					},1000);
					//给所有的button绑定点击事件
					$(document).on('click','button',function(){
						var btnTex = $(this).text();
						for(var i = 0;i < data.length;i++){
							if (btnTex == data[i].color) {
								$('.good_img img')[0].src = data[i].show_pic;
							}
							changePriceAndstock();	//选择商品类型的时候调用改变颜色和价格
						}
					});
					//改变信息框的颜色和价格
					function changePriceAndstock () {
						for (var j = 0;j < data.length;j++) {
							if (skuGroup == data[j].sku_combination) {
								$('.price').text(data[j].cash_price);
								$('.info_stock').text(data[j].stock);
								$('.selected').text(data[j].shuxing_zhi.replace(/'/g,''));
								localStorage.setItem('JFSCpic',data[j].show_pic);		//商品缩略图
								localStorage.setItem('JFSCyixuan',data[j].shuxing_zhi);	//商品属性
								localStorage.setItem('JFSCprice',data[j].cash_price);   //商品价格
								localStorage.setItem('skuId',data[j].sku_combination);	//skuid
								//getSkuStock(data[j].stock);	//获取单个商品sku库存
							}
						}
					}
					changePriceAndstock();	//页面加载的时候调用一次改变颜色和价格
				}
			},
			error: function(err) {
				console.log(err)
			}
		});
	}

	//html标签反转译
	function HTMLDecode(text) {
		var temp = document.createElement("div");
		temp.innerHTML = text;
		var output = temp.innerText || temp.textContent;
		temp = null;
		return output;
	}

	//点击购物车小图标跳转到购物车页面
	$('.shop_car').bind('click', function() {
		console.log('跳转到购物车...')
		window.location.href = '/Product/Zero/gouwuche.html';
	});
	//点击首页按钮跳转到首页
	$('.foot_li_Lt').bind('click', function() {
		console.log('跳转到首页...');
		window.location.href = '/Product/Shopindex/index.html';
	});
	//关闭商品信息
	$(".good_Info .close").click(function() {
		$('.detail_foot').css('display', 'block');
		$('.detail_footTwo').css("display", "none");
		$('.detail_footThree').css("display", "none");
		$('.detail_footFour').css("display", "none");
		$(".good_Info").css("display", "none");
		$(".mask").css("display", "none");
	});

	//商品数量加减 
	$(".buy_num .add").click(function() {
//		if (obj.goodNum.val() >= obj.skuStock) {
//			$(".errAlert").text("商品数量不能超出库存").addClass("AlertShow");
//			setTimeout(function() {
//				$(".errAlert").removeClass("AlertShow");
//			}, 3000);
//		} else{
			obj.goodNum.val(parseInt(obj.goodNum.val()) + 1);
			$(".buy_num .reduce").removeAttr("disabled"); //当按加1时，设置$(".buy_num .reduce")为可点击状态
//		}
	});
	//数量减按钮  
	$(".buy_num .reduce").click(function() {
		if(parseInt(obj.goodNum.val()) > 1) { //判断数量值大于1时才可以减少  
			obj.goodNum.val(parseInt(obj.goodNum.val()) - 1)
		} else {
			$(".buy_num .reduce").attr("disabled", true); //当num为1时，设置$(".buy_num .reduce")为不可点击状态
			$(".errAlert").text("商品数量至少为一件").addClass("AlertShow");
			setTimeout(function() {
				$(".errAlert").removeClass("AlertShow");
			}, 3000);
		} 
	});
	
	//点击选择套餐类型，颜色分类时弹出商品信息
	$(".good_information .package-color").click(function() {
		$('.detail_foot').css('display', 'none');
		$('.detail_footTwo').css("display", "block");
		$(".good_Info").css("display", "block");
		$(".mask").css("display", "block");
		//加入购物车
		$('.shopingCarTwo').click(function(event){
			event.stopPropagation();
			$.ajax({  
			    url:'http://a.91jfk.com/Product/Pointcart/add_cart',
			    data:{
			    	id:obj.id,
			    	num:obj.goodNum.val(),
			    	sku_combination:skuGroup.toString(),
			    	model:obj.type
			    },
			    type:'post',  
			    dataType:'json',  
			    success:function(res) { 
			    	console.log(res);
			        if(res.code =="1"){  
			        	$(".errAlert").text(res.message).addClass("AlertShow");
						setTimeout(function() {
							$(".errAlert").removeClass("AlertShow");
						}, 2000);
			            window.loaction.reload();
			       }else{  
				        $(".errAlert").text(res.message).addClass("AlertShow");
						setTimeout(function() {
							$(".errAlert").removeClass("AlertShow");
							location.reload();
						}, 2000);  
			        }  
			    },  
			    error : function(err) {    
			        console.log(err);
			    }  
			});//ajax结束
		});
		//立即购买
		$('.farstBuyTwo').click(function(event){
			event.stopPropagation();
			localStorage.setItem('JFSCid',obj.id);				//商品id
			localStorage.setItem('JFSCnum',obj.goodNum.val());	//商品数量
			window.location.href = '/Product/Zero/point_shop_confirmOrder.html';
		});
	});

	//加入购物车
	$(".detail_foot .shopingCar").bind("click", function() {
		$('.detail_foot').css('display', 'none');
		$('.detail_footThree').css("display", "block");
		$(".good_Info").css("display", "block");
		$(".mask").css("display", "block");
		$('.detail_footThree').click(function(){
			console.log(obj.id,obj.goodNum.val(),skuGroup.toString(),obj.type);
			$.ajax({  
			    url:'http://a.91jfk.com/Product/Pointcart/add_cart',
			    data:{
			    	id:obj.id,
			    	num:obj.goodNum.val(),
			    	sku_combination:skuGroup.toString(),
			    	model:obj.type
			    },
			    type:'post',  
			    dataType:'json',  
			    success:function(res) { 
			    	console.log(res);
			        if(res.code =="1"){  
			        	$(".errAlert").text(res.message).addClass("AlertShow");
						setTimeout(function() {
							$(".errAlert").removeClass("AlertShow");
			            	location.reload();
						}, 2000);
			        }else{
				        $(".errAlert").text(res.message).addClass("AlertShow");
						setTimeout(function() {
							$(".errAlert").removeClass("AlertShow");
						}, 2000);  
			        }  
			    },  
			    error : function(err) {    
			        console.log(err);
			    }  
			});//ajax结束
		});
	}); //点击事件结束

	//立即购买
	$(".detail_foot .farstBuy").bind("click", function() {
		$('.detail_foot').css('display', 'none');
		$('.detail_footFour').css("display", "block");
		$(".good_Info").css("display", "block");
		$(".mask").css("display", "block");
		$('.detail_footFour').click(function(){
			localStorage.setItem('JFSCid',obj.id);				//商品id
			localStorage.setItem('JFSCnum',obj.goodNum.val());	//商品数量
			window.location.href = '/Product/Zero/point_shop_confirmOrder.html';
		});
	}); //点击事件结束

	function Sku(arr) {
		var data = arr;
		var res = {};
		var spliter = '&';
		var r = {};
		var keys = [];
		var selectedCache = [];
		/**
		 * 计算组合数据
		 */
		function combineAttr(data, keys) {
			var allKeys = [];
			var result = {};
			for(var i = 0; i < data.length; i++) {
				var item = data[i];
				var values = [];
				for(var j = 0; j < keys.length; j++) {
					var key = keys[j];
					if(!result[key]) result[key] = [];
					if(result[key].indexOf(item[key]) < 0) result[key].push(item[key])
					values.push(item[key])
				}
				allKeys.push({
					path: values.join(spliter),
					sku: item['skuId']
				})
			}
			console.log(allKeys);
			return {
				result: result,
				items: allKeys
			}
		}
		/**
		 * 渲染 DOM 结构
		 */
		function render(data) {
			var output = '';
			for(var i = 0; i < keys.length; i++) {
				var key = keys[i];
				var items = data[key];
				output += '<div class="package classification" data-type="' + key + '" data-idx="' + i + '">'
				output += '<p class="classify">' + key + ':</p>'
				output += '<p class="chosePackage">'
				for(var j = 0; j < items.length; j++) {
					var item = items[j];
					var cName = j == 0 ? 'change' : '';
					if(j == 0) {
						selectedCache.push(item)
					}
					output += '<button data-title="' + item + '"class="' + cName + '"value="' + item + '">' + item + '</button>'
				}
				output += '</p>'
				output += '</div>'
			}
			output += '</div>'
			$('.Info_contentTop').html(output);
		}

		function getAllKeys(arr) {
			var result = [];
			for(var i = 0; i < arr.length; i++) {
				result.push(arr[i].path)
			}
			return result
		}

		function powerset(arr) {
			var ps = [
				[]
			];
			for(var i = 0; i < arr.length; i++) {
				for(var j = 0, len = ps.length; j < len; j++) {
					ps.push(ps[j].concat(arr[i]));
				}
			}
			return ps;
		}
		/**
		 * 生成所有子集是否可选、库存状态 map
		 */
		function buildResult(items) {
			var allKeys = getAllKeys(items)
			for(var i = 0; i < allKeys.length; i++) {
				var curr = allKeys[i];
				var sku = items[i].sku;
				var values = curr.split(spliter);
				var allSets = powerset(values);
				// 每个组合的子集
				for(var j = 0; j < allSets.length; j++) {
					var set = allSets[j];
					var key = set.join(spliter);
					if(res[key]) {
						res[key].skus.push(sku);
					} else {
						res[key] = {
							skus: [sku]
						}
					}
				}
			}
		}

		function trimSpliter(str, spliter) {
			// ⊙abc⊙ => abc
			// ⊙a⊙⊙b⊙c⊙ => a⊙b⊙c
			var reLeft = new RegExp('^' + spliter + '+', 'g');
			var reRight = new RegExp(spliter + '+$', 'g');
			var reSpliter = new RegExp(spliter + '+', 'g');
			return str.replace(reLeft, '').replace(reRight, '').replace(reSpliter, spliter);
		}
		/**
		 * 获取当前选中的属性
		 */
		function getSelectedItem() {
			var result = [];
			$('div[data-type]').each(function() {
				var $selected = $(this).find('.change')
				if($selected.length) {
					result.push($selected.val());
				} else {
					result.push('');
				}
			})
			return result;
		}
		/**
		 * 更新所有属性状态
		 */
		function updateStatus(selected) {
			for(var i = 0; i < keys.length; i++) {
				var key = keys[i];
				var data = r.result[key];
				var hasActive = !!selected[i];
				var copy = selected.slice();
				for(var j = 0; j < data.length; j++) {
					var item = data[j];
					if(selected[i] == item) continue
					copy[i] = item
					var curr = trimSpliter(copy.join(spliter), spliter);
					var $item = $('.package.classification').filter('[data-type="' + key + '"]').find('[value="' + item + '"]');
					var titleStr = '[' + copy.join('-') + ']';
					if(res[curr]) {
						$item.removeClass('disabled');
						setTitle($item.get(0));
					} else {
						$item.addClass('disabled').attr('title', titleStr + ' 无此属性搭配');
					}
				}
			}
		}
		/**
		 * 正常属性点击
		 */
		function handleNormalClick($this) {
			$this.siblings().removeClass('change');
			$this.addClass('change');
		}
		/**
		 * 无效属性点击
		 */
		function handleDisableClick($this) {
			var $currAttr = $this.parents('.package.classification').eq(0);
			var idx = $currAttr.data('idx');
			var type = $currAttr.data('type');
			var value = $this.val();
			$this.removeClass('disabled');
			selectedCache[idx] = value;
			// 清空高亮行的已选属性状态（因为更新的时候默认会跳过已选状态）
			$('.package.classification').not($currAttr).find('button').removeClass('change');
			updateStatus(getSelectedItem());
			/**
			 * 恢复原来已选属性
			 * 遍历所有非当前属性行
			 *   1. 与 selectedCache 对比
			 *   2. 如果要恢复的属性存在（非 disable）且 和当前*未高亮行*已选择属性的*可组合*），高亮原来已选择的属性且更新
			 *   3. 否则什么也不做
			 */
			for(var i = 0; i < keys.length; i++) {
				var item = keys[i];
				var $curr = $('div[data-type="' + item + '"]');
				if(item == type) continue
				var $lastSelected = $curr.find('button[value="' + selectedCache[i] + '"]');
				// 缓存的已选属性没有 disabled (可以被选择)
				if(!$lastSelected.hasClass('disabled')) {
					$lastSelected.addClass('change');
					updateStatus(getSelectedItem());
				}
			}
		}
		/**
		 * 高亮当前属性区
		 */
		function highLighAttr() {
			for(var i = 0; i < keys.length; i++) {
				var key = keys[i];
				var $curr = $('div[data-type="' + key + '"]')
				if($curr.find('.change').length < 1) {
					$curr.addClass('hl');
				} else {
					$curr.removeClass('hl');
				}
			}
		}

		function bindEvent() {
			$('.Info_contentTop').undelegate().delegate('button', 'click', function(e) {
				var $this = $(this);
				var isActive = $this.hasClass('.change');
				var isDisable = $this.hasClass('disabled');
				if(!isActive) {
					handleNormalClick($this)
					if(isDisable) {
						handleDisableClick($this);
					} else {
						selectedCache[$this.parents('.package.classification').eq(0).data('idx')] = $this.val();
					}
					updateStatus(getSelectedItem());
					highLighAttr();
					showResult();
				}
			})
			$('button').each(function() {
				var value = $(this).val();
				if(!res[value] && !$(this).hasClass('change')) {
					$(this).addClass('disabled');
				}
			})
		}

		function showResult() {
			var result = getSelectedItem();
			var s = [];
			for(var i = 0; i < result.length; i++) {
				var item = result[i];
				if(!!item) {
					s.push(item)
				}
			}
			if(s.length == keys.length) {
				var curr = res[s.join(spliter)];
				ss = s;
				if(curr) {
					ss = ss.concat(curr.skus);
				}
				console.log(ss);
				getSkuGroup(curr.skus);
			}
		}

		function setTitle(el) {
			var title = $(el).data('title');
			if(title) $(el).attr('title', title);
		}

		function setAllTitle() {
			$('.Info_contentTop').find('button').each(setTitle);
		}

		function init(data) {
			res = {};
			r = {};
			keys = [];
			selectedCache = [];
			for(var attr_key in data[0]) {
				if(!data[0].hasOwnProperty(attr_key)) continue;
				if(attr_key != 'skuId') keys.push(attr_key);
			}
			setAllTitle();
			r = combineAttr(data, keys);
			render(r.result);
			buildResult(r.items);
			updateStatus(getSelectedItem());
			showResult();
			bindEvent();
		}
		init(data);
	}
});